import { ref, onMounted } from 'vue'

/**
 * 分页可以单独做个PageWrapper, 只要传方法和table就行，但是调用方法麻烦，不如react灵活，就不封装了
 * @param {*} fun 
 * @param {*} onLoad  //第一次进来是否加载
 * @returns 
 */
function index(fun, onLoad) {
    const loading = ref(false)
    const pageNum = ref(1)
    const pageSize = ref(20)

    const tableData = ref({ total: 0, records: [] })

    onMounted(() => {
        onLoad && getList()
    })

    async function getList() {
        loading.value = true
        const res = await fun(pageNum.value, pageSize.value)
        loading.value = false
        if (res) {
            tableData.value = {
                total: res.total || res.count,
                records: res.results || res.list || res.records || res || [],
            };
        } else {
            tableData.value = {
                total: 0,
                records: []
            }
        }
    }

    const clear = () => {
        loading.value = false
        pageNum.value = 1
        tableData.value = { total: 0, records: [] }
    }

    const refresh = () => {
        pageNum.value = 1
        getList()
    }

    /**
     * 删除的时候检查当前删除项是不是当页最后一个
     * @param {*} check 
     */
    const refreshCurrent = () => {
        getList()
    }

    const sizeChange = (size) => {
        pageSize.value = size
        refresh()
    }

    const selectPage = (pageNo) => {
        pageNum.value = pageNo
        getList()
    }

    return { clear, loading, pageNum, pageSize, tableData, sizeChange, selectPage, refresh, refreshCurrent }
}

export default index
